ANÁLISIS DE PARIS (TP FINAL)

COLEGIOS

París DATA

En este ultimo ejercicio “TP FINAL” continuare con el análisis de información relativa a los colegios en la ciudad de París, de modo tal robustecer el análisis ya realizado incorporando la conectividad de wifi por cada establecimiento con la intención de analizar la accesibilidad a un servicio de internet público por parte de los estudiantes de los distintos colegios.

En primer lugar instalo las librerías que voy a requerir.

options(repos = c(CRAN = "https://cran.r-project.org"))
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.3
## Warning: package 'ggplot2' was built under R version 4.2.3
## Warning: package 'tibble' was built under R version 4.2.3
## Warning: package 'tidyr' was built under R version 4.2.3
## Warning: package 'readr' was built under R version 4.2.3
## Warning: package 'purrr' was built under R version 4.2.3
## Warning: package 'dplyr' was built under R version 4.2.3
## Warning: package 'stringr' was built under R version 4.2.3
## Warning: package 'forcats' was built under R version 4.2.3
## Warning: package 'lubridate' was built under R version 4.2.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(sf)
## Linking to GEOS 3.9.1, GDAL 3.3.2, PROJ 7.2.1; sf_use_s2() is TRUE
library(ggplot2)

Cargo la información de los diferentes barrios de la ciudad de París descargada de la página de París DATA y corroboro su morfología mapeando los datos.

paris<- st_read("Data/arrondissements.geojson", stringsAsFactors = TRUE)
## Reading layer `arrondissements' from data source 
##   `C:\Users\Asus\OneDrive - Ministerio de Vivienda y Urbanismo\Documentos\Zoom\Escritorio\Torcuato Di Tella\Instrumentos de Analisis Urbano II\TP2_IAU2\TP_FINAL_IAU2_MEU\TP_FINAL_IAU2_MEU\Data\arrondissements.geojson' 
##   using driver `GeoJSON'
## Simple feature collection with 20 features and 9 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: 2.224075 ymin: 48.81558 xmax: 2.469761 ymax: 48.90216
## Geodetic CRS:  WGS 84
ggplot()+
  geom_sf(data=paris)

Con el archivo cargado y corroborado procedo a subir los datos de los establecimientos escolares; colegio. Los mapeo.

colegios<- st_read("Data/etablissements-scolaires-colleges.geojson", stringsAsFactors = TRUE)
## Reading layer `etablissements-scolaires-colleges' from data source 
##   `C:\Users\Asus\OneDrive - Ministerio de Vivienda y Urbanismo\Documentos\Zoom\Escritorio\Torcuato Di Tella\Instrumentos de Analisis Urbano II\TP2_IAU2\TP_FINAL_IAU2_MEU\TP_FINAL_IAU2_MEU\Data\etablissements-scolaires-colleges.geojson' 
##   using driver `GeoJSON'
## Simple feature collection with 566 features and 8 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: 2.254942 ymin: 48.81844 xmax: 2.411708 ymax: 48.89861
## Geodetic CRS:  WGS 84
names(colegios)
## [1] "adresse"      "arr_libelle"  "arr_insee"    "id_projet"    "libelle"     
## [6] "annee_scol"   "type_etabl"   "geo_point_2d" "geometry"
ggplot() +
    geom_sf(data = paris) +
  geom_sf(data = colegios, color = "orange")

Transformo el archivo de colegios en uno georeferenciado para poder luego hacer un JOIN espacial.

cole_geo <- colegios %>% 
    st_as_sf(coords = c("long", "lat"), crs = 4326)
class(cole_geo)
## [1] "sf"         "data.frame"
head(cole_geo)
## Simple feature collection with 6 features and 8 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: 2.277839 ymin: 48.84129 xmax: 2.378877 ymax: 48.89861
## Geodetic CRS:  WGS 84
##                      adresse arr_libelle arr_insee
## 1    149 boulevard MacDonald  19ème Ardt     75119
## 2 77 bis BOULEVARD DE CLICHY   9ème Ardt     75109
## 3            14 RUE DE STAEL  15ème Ardt     75115
## 4               88 rue MONGE   5ème Ardt     75105
## 5    13 rue EUGENE DELACROIX  16ème Ardt     75116
## 6              6 rue MOLIERE    1er Ardt     75101
##                                         id_projet                libelle
## 1 COLLEGES (année scolaire 2017/2018 - 2018/2019)         SUZANNE LACORE
## 2 COLLEGES (année scolaire 2017/2018 - 2018/2019)            JULES FERRY
## 3 COLLEGES (année scolaire 2017/2018 - 2018/2019)        MADAME DE STAEL
## 4 COLLEGES (année scolaire 2017/2018 - 2018/2019)         PIERRE ALVISET
## 5 COLLEGES (année scolaire 2017/2018 - 2018/2019)       EUGENE DELACROIX
## 6 COLLEGES (année scolaire 2017/2018 - 2018/2019) JEAN-BAPTISTE POQUELIN
##   annee_scol type_etabl        geo_point_2d                  geometry
## 1       <NA>       <NA> 48.898609, 2.378877 POINT (2.378877 48.89861)
## 2       <NA>       <NA> 48.884350, 2.329146 POINT (2.329146 48.88435)
## 3       <NA>       <NA> 48.843618, 2.310171 POINT (2.310171 48.84362)
## 4       <NA>       <NA> 48.841295, 2.351784 POINT (2.351784 48.84129)
## 5       <NA>       <NA> 48.862606, 2.277839 POINT (2.277839 48.86261)
## 6       <NA>       <NA> 48.864653, 2.335488 POINT (2.335488 48.86465)
ggplot(cole_geo)+
  geom_sf()

ggplot()+
  geom_sf(data=paris, fill="gray75", color="white")+
  geom_sf(data=cole_geo, aes(color=arr_libelle), alpha=0.5)+
  labs(title="Escuelas de Paris")

A continuación realizo el JOIN espacial entre el archivos de barrios y colegios para poder tener la información de barrios dentro de colegios.

cole_geo <- st_join(cole_geo, paris)
ggplot()+
  geom_sf(data=paris)+
  geom_sf(data=cole_geo, aes(color=arr_libelle), alpha=0.75, show.legend = FALSE)

Filtro los valores sin dato.

cole_geo <- cole_geo %>%
  filter(!is.na(arr_libelle))

Vuelvo a mapear los barrios y colegios con un color diferente por cada barrio.

ggplot()+
  geom_sf(data=paris)+
  geom_sf(data=cole_geo, aes(color=arr_libelle), alpha=0.75, show.legend = FALSE)

PROCESAMIENTO DE DATOS

Procedo a crear dos columnas/campos nuevos. Uno sobre la cantidad de colegios por barrio y otro de densidad de colegios para lo cual usare la reciente columna creada de cantidad junto a los valores de superficie de cada barrio.

colnames(cole_geo)
##  [1] "adresse"      "arr_libelle"  "arr_insee"    "id_projet"    "libelle"     
##  [6] "annee_scol"   "type_etabl"   "geo_point_2d" "c_ar"         "l_aroff"     
## [11] "surface"      "l_ar"         "n_sq_co"      "c_arinsee"    "n_sq_ar"     
## [16] "perimetre"    "geom_x_y"     "geometry"
cole_geo <- cole_geo %>%
  group_by(l_ar) %>%
  summarise(cantidad=n(),
            densidad_cole=mean(cantidad/surface))

Vemos que las columnas se crearon correctamente.

head(cole_geo)
## Simple feature collection with 6 features and 3 fields
## Geometry type: MULTIPOINT
## Dimension:     XY
## Bounding box:  xmin: 2.27859 ymin: 48.81844 xmax: 2.411708 ymax: 48.88162
## Geodetic CRS:  WGS 84
## # A tibble: 6 × 4
##   l_ar       cantidad densidad_cole                                     geometry
##   <fct>         <int>         <dbl>                             <MULTIPOINT [°]>
## 1 10ème Ardt       25    0.00000865 ((2.371691 48.87485), (2.371691 48.87485), …
## 2 11ème Ardt       30    0.00000818 ((2.374321 48.86823), (2.374321 48.86823), …
## 3 12ème Ardt       35    0.00000215 ((2.386163 48.84831), (2.386163 48.84831), …
## 4 13ème Ardt       55    0.00000769 ((2.358379 48.81844), (2.358379 48.81844), …
## 5 14ème Ardt       30    0.00000534 ((2.314972 48.83426), (2.314972 48.83426), …
## 6 15ème Ardt       40    0.00000471 ((2.27859 48.83886), (2.27859 48.83886), (2…

Luego mapeo los datos de densidad de colegios por barrio, sin tener la información volcada sobre los polígonos.

ggplot()+
  geom_sf(data=paris)+
  geom_sf(data=cole_geo, aes(color=densidad_cole), alpha=0.75, show.legend = FALSE)

TRASPASO DE INFORMACIÓN A POLÍGONOS

En consecuencia, decido pasar la data a los polígono correspondientes para lo cual tendré que sacarle la geometría al archivo de colegio para poder realizar un LEFT JOIN ya que esta herramienta sólo une archivos espaciales con no espaciales, no así, dos geográficos a la vez.

cole_geo <- cole_geo %>%
  st_set_geometry(NULL)
head(cole_geo)
## # A tibble: 6 × 3
##   l_ar       cantidad densidad_cole
##   <fct>         <int>         <dbl>
## 1 10ème Ardt       25    0.00000865
## 2 11ème Ardt       30    0.00000818
## 3 12ème Ardt       35    0.00000215
## 4 13ème Ardt       55    0.00000769
## 5 14ème Ardt       30    0.00000534
## 6 15ème Ardt       40    0.00000471

Se puede apreciar que el archivo se ejecuta correctamente sacando la información geográfica. Ahora realizo el LEFT JOIN y mapeo para verificar que todo haya resultado bien.

paris_b <- left_join(paris, cole_geo, by="l_ar")
ggplot()+
  geom_sf(data=paris_b, aes(fill=densidad_cole))

DENSIDAD DE COLEGIOS

Una vez verificado con el mapa, decido editarlo para presentar los resultados finales.

ggplot()+
  geom_sf(data=paris_b, aes(fill=densidad_cole), color="white")+
    labs(title = "Densidad de colegios en la ciudad de Paris",
         subtitle = "Barrios de Paris",
         fill = "Cantidad/sup",
         caption= "Fuente: Paris DATA") +
  scale_fill_distiller(palette = "YlOrRd", direction = 1) +
   theme_void()

CANTIDAD DE COLEGIOS

A continuación mostrare la cantidad de colegios por barrio de la ciudad de París con el archivo de Colegios. De esta forma podre analizar cuales son los barrios con mayor cantidad de colegios a través de un gráfico de barras.

ggplot(colegios)+
  geom_bar(aes(x=arr_libelle ))+
  coord_flip()+
  labs(title="Cantidad total de colegios por Barrio",
       x="Barrios",
       y="Cantidad",
       caption="Fuente: Paris DATA")+
  theme(legend.position="top",
        legend.direction = "horizontal", 
        legend.title=element_text(size=8, face = "bold"), 
        legend.text=element_text(size=8), 
        axis.text.x = element_text(colour = "gray35",size = 6), 
        axis.text.y = element_text(colour = "gray35",size = 1))

Finalmente, mapeo esta información con el archivo de polígonos.

ggplot()+
  geom_sf(data=paris_b, aes(fill=cantidad), color="white")+
    labs(title = "Cantidad de colegios en la ciudad de Paris",
         subtitle = "Barrios de Paris",
         fill = "Cantidad",
         caption= "Fuente: Paris DATA") +
  scale_fill_distiller(palette = "YlGnBu", direction = 1) +
   theme_void()

CONCLUSIONES

Decido realizar un resumen estadístico de la información como se puede ver:

summary(paris_b)
##       c_ar                      l_aroff      surface                 l_ar   
##  Min.   : 1.00   Batignolles-Monceau: 1   Min.   :  991154   10ème Ardt: 1  
##  1st Qu.: 5.75   Bourse             : 1   1st Qu.: 2172001   11ème Ardt: 1  
##  Median :10.50   Buttes-Chaumont    : 1   Median : 3985047   12ème Ardt: 1  
##  Mean   :10.50   Buttes-Montmartre  : 1   Mean   : 5268639   13ème Ardt: 1  
##  3rd Qu.:15.25   Élysée             : 1   3rd Qu.: 6195201   14ème Ardt: 1  
##  Max.   :20.00   Entrepôt           : 1   Max.   :16372542   15ème Ardt: 1  
##                  (Other)            :14                      (Other)   :14  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##     n_sq_co          c_arinsee        n_sq_ar          perimetre    
##  Min.   :7.5e+08   Min.   :75101   Min.   :7.5e+08   Min.   : 4519  
##  1st Qu.:7.5e+08   1st Qu.:75106   1st Qu.:7.5e+08   1st Qu.: 6413  
##  Median :7.5e+08   Median :75111   Median :7.5e+08   Median : 8191  
##  Mean   :7.5e+08   Mean   :75111   Mean   :7.5e+08   Mean   : 9522  
##  3rd Qu.:7.5e+08   3rd Qu.:75115   3rd Qu.:7.5e+08   3rd Qu.:10895  
##  Max.   :7.5e+08   Max.   :75120   Max.   :7.5e+08   Max.   :24090  
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##                                                                     
##  geom_x_y.Length  geom_x_y.Class  geom_x_y.Mode    cantidad    
##  2        -none-   numeric                      Min.   : 5.00  
##  2        -none-   numeric                      1st Qu.:10.00  
##  2        -none-   numeric                      Median :25.50  
##  2        -none-   numeric                      Mean   :28.30  
##  2        -none-   numeric                      3rd Qu.:36.25  
##  2        -none-   numeric                      Max.   :65.00  
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  2        -none-   numeric                                     
##  densidad_cole                geometry 
##  Min.   :1.588e-06   POLYGON      :20  
##  1st Qu.:4.450e-06   epsg:4326    : 0  
##  Median :6.211e-06   +proj=long...: 0  
##  Mean   :6.290e-06                     
##  3rd Qu.:8.777e-06                     
##  Max.   :1.003e-05                     
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
##                                        
## 

Se puede detectar algunos detalles:

  • El barrio con mayor cantidad de colegios es el distrito 19 Buttes-Chaumont y tiene 65 establecimientos.
  • Los barrios con menor cantidad de colegios son el distrito 1 y 2 (Louvre y Bourse) y ambos tienen 5 establecimientos cada uno.
  • La fuente de todas las observaciones eshttps://opendata.paris.fr/pages/home/
  • La cantidad promedio es de 28 colegios por barrio.

En base al análisis general decido profundizar más en los 5 barrios con mayor cantidad de colegios:

ordenado <- paris_b %>%
  
arrange(desc(cantidad))

head(ordenado,5)
## Simple feature collection with 5 features and 11 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: 2.262959 ymin: 48.81558 xmax: 2.416431 ymax: 48.90216
## Geodetic CRS:  WGS 84
##   c_ar           l_aroff surface       l_ar   n_sq_co c_arinsee   n_sq_ar
## 1   19   Buttes-Chaumont 6792651 19ème Ardt 750001537     75119 750000019
## 2   20      Ménilmontant 5983446 20ème Ardt 750001537     75120 750000020
## 3   18 Buttes-Montmartre 5996051 18ème Ardt 750001537     75118 750000018
## 4   13          Gobelins 7149311 13ème Ardt 750001537     75113 750000013
## 5   15         Vaugirard 8494994 15ème Ardt 750001537     75115 750000015
##   perimetre            geom_x_y cantidad densidad_cole
## 1 11253.182 48.887076, 2.384821       65  9.569165e-06
## 2 10704.940 48.863461, 2.401188       60  1.002767e-05
## 3  9916.464 48.892569, 2.348161       55  9.172703e-06
## 4 11546.547 48.828388, 2.362272       55  7.693049e-06
## 5 13678.798 48.840085, 2.292826       40  4.708655e-06
##                         geometry
## 1 POLYGON ((2.389428 48.90122...
## 2 POLYGON ((2.412765 48.87547...
## 3 POLYGON ((2.365804 48.88554...
## 4 POLYGON ((2.374913 48.83801...
## 5 POLYGON ((2.299322 48.85217...
  1. Buttes-Chaumont
  2. Ménilmontant
  3. Buttes-Montmartre
  4. Gobelins
  5. Vaugirard

Por otro lado, los 5 barrios con más densidad de colegios son:

ordenado_b <- paris_b %>%
  
arrange(desc(densidad_cole))

head(ordenado_b,5)
## Simple feature collection with 5 features and 11 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: 2.32559 ymin: 48.83678 xmax: 2.416431 ymax: 48.90216
## Geodetic CRS:  WGS 84
##   c_ar           l_aroff surface       l_ar   n_sq_co c_arinsee   n_sq_ar
## 1   20      Ménilmontant 5983446 20ème Ardt 750001537     75120 750000020
## 2    5          Panthéon 2539375  5ème Ardt 750001537     75105 750000005
## 3   19   Buttes-Chaumont 6792651 19ème Ardt 750001537     75119 750000019
## 4    9             Opéra 2178303  9ème Ardt 750001537     75109 750000009
## 5   18 Buttes-Montmartre 5996051 18ème Ardt 750001537     75118 750000018
##   perimetre            geom_x_y cantidad densidad_cole
## 1 10704.940 48.863461, 2.401188       60  1.002767e-05
## 2  6239.195 48.844443, 2.350715       25  9.844944e-06
## 3 11253.182 48.887076, 2.384821       65  9.569165e-06
## 4  6471.588 48.877164, 2.337458       20  9.181458e-06
## 5  9916.464 48.892569, 2.348161       55  9.172703e-06
##                         geometry
## 1 POLYGON ((2.412765 48.87547...
## 2 POLYGON ((2.364433 48.84614...
## 3 POLYGON ((2.389428 48.90122...
## 4 POLYGON ((2.339777 48.88203...
## 5 POLYGON ((2.365804 48.88554...
  1. Ménilmontant
  2. Panthéon
  3. Buttes-Chaumont
  4. Opéra
  5. Buttes-Montmartre

TP FINAL

PARIS

París DATA

CONECTIVIDAD

En esta final, procedo a cargar la base de datos de puntos o sitios con disponibilidad de acceso a WIFI. Con la intención de analizar la accesibilidad a un servicio de internet público por parte de los estudiantes de los distintos colegios.Finalmente incorporare otro tipo de servicios como “comercios”.

wifi<- st_read("Data/sites-disposant-du-service-paris-wi-fi.geojson", stringsAsFactors = TRUE)
## Reading layer `sites-disposant-du-service-paris-wi-fi' from data source 
##   `C:\Users\Asus\OneDrive - Ministerio de Vivienda y Urbanismo\Documentos\Zoom\Escritorio\Torcuato Di Tella\Instrumentos de Analisis Urbano II\TP2_IAU2\TP_FINAL_IAU2_MEU\TP_FINAL_IAU2_MEU\Data\sites-disposant-du-service-paris-wi-fi.geojson' 
##   using driver `GeoJSON'
## Simple feature collection with 277 features and 7 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: 2.255095 ymin: 48.76286 xmax: 2.499478 ymax: 48.93255
## Geodetic CRS:  WGS 84

Mapeare los datos para analizar su distribución geográfica y poder saber los valores de coordenadas en LONGITUD y LATITUD de las dos bases de datos principales, puntos de wifi y colegios.

ggplot()+
   geom_sf(data = paris) +
  geom_sf(data=wifi)

colegios_b <- colegios %>%
  mutate(lat_int = gsub( ",.*" , "", geometry), 
         lon_int = gsub(".*," , "", geometry ) )
colegios_b <- colegios_b %>%
  mutate(latitude = as.numeric(str_remove(lat_int, "c\\(")), 
         longitude = as.numeric(str_remove(lon_int, "\\)" )))
wifi_b <- wifi %>%
  mutate(lat_int = gsub( ",.*" , "", geometry), 
         lon_int = gsub(".*," , "", geometry ) )
wifi_b <- wifi_b %>%
  mutate(latitude = as.numeric(str_remove(lat_int, "c\\(")), 
         longitude = as.numeric(str_remove(lon_int, "\\)" )))

Cargare el mapa base de fondo para tener una mejor visualización de París que es la ciudad en la que estoy trabajando y configurare el CRS o sistema de coordenadas de las bases de datos de puntos.

library(ggmap)
## Warning: package 'ggmap' was built under R version 4.2.1
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
bbox <- st_bbox(paris)
class(bbox)
## [1] "bbox"
bbox <- as.numeric(bbox)
class(bbox)
## [1] "numeric"
mapa_base <- get_stamenmap(bbox = bbox, 
                           maptype = "terrain", 
                           zoom = 12)
## Source : http://tile.stamen.com/terrain/12/2073/1408.png
## Source : http://tile.stamen.com/terrain/12/2074/1408.png
## Source : http://tile.stamen.com/terrain/12/2075/1408.png
## Source : http://tile.stamen.com/terrain/12/2076/1408.png
## Source : http://tile.stamen.com/terrain/12/2073/1409.png
## Source : http://tile.stamen.com/terrain/12/2074/1409.png
## Source : http://tile.stamen.com/terrain/12/2075/1409.png
## Source : http://tile.stamen.com/terrain/12/2076/1409.png
ggmap(mapa_base) + 
  geom_sf(data = paris, inherit.aes = FALSE, fill = NA) + 
  geom_sf(data = colegios_b, inherit.aes = FALSE, alpha = 0.5, color = "blue") +
  geom_sf(data = wifi_b, inherit.aes = FALSE, color = "magenta", size =1) + 
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

colegios_geo <- st_as_sf(colegios_b, coords = c("longitude", "latitude"), crs = 4326)
wifi_geo <- st_as_sf(wifi_b, coords = c("longitude", "latitude"), crs=4326)
ggmap(mapa_base) + 
  geom_sf(data = paris, inherit.aes = FALSE, fill = NA, size =1) + 
  geom_sf(data = colegios_geo,  alpha = 0.5, inherit.aes = FALSE, color = "blue") +
  geom_sf(data = wifi_geo,  color = "magenta", size = 1, inherit.aes = FALSE) + 
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

Antes de realizar los buffer de los colegios, decidí ver el sistema de medidas, al estar en NULL, lo cambie de acuerdo a la ciudad en la que estoy trabajando. De esta forma paso a metros el sistema de medidas lo cual nos permitirá realizar los buffers.

st_crs(colegios_geo)$units
## NULL
st_crs(wifi_geo)$units
## NULL
colegios_reproyectados <- colegios_geo %>%
  st_transform(crs = 2154)
wifi_reproyectados <- wifi_geo %>%
  st_transform(crs = 2154)
st_crs(colegios_reproyectados)$units
## [1] "m"

Realizo un buffer por cada punto de colegio de 500 metros, una distancia considerable de forma peatonal para que los estudiantes puedan acceder a Puntos de WIFI en la proximidad de sus establecimientos educativos.

buffer_colegios <- st_buffer(colegios_reproyectados, 500)
ggplot() + 
  geom_sf(data =buffer_colegios ) + 
  geom_sf(data =colegios ) 

Cruzo los datos de los Puntos WIFI con los buffers de colegios para poder analizar su cantidad.

wifi_en_buffer <- st_intersection(wifi_reproyectados, buffer_colegios)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
wifi_x_colegios <- wifi_en_buffer %>%
  st_set_geometry(NULL) %>%
  group_by(libelle) %>%
  summarise(cantidad =n())
ordenado <- wifi_x_colegios %>%
  
arrange(desc(cantidad))

head(ordenado,5)
## # A tibble: 5 × 2
##   libelle           cantidad
##   <fct>                <int>
## 1 FRANCOIS COUPERIN       95
## 2 CHARLEMAGNE             50
## 3 CESAR FRANCK            45
## 4 ELSA TRIOLET            40
## 5 VICTOR HUGO             35

Se puede concluir que los 3 colegios de Paris con mayor cantidad de Puntos WIFI cercanos son Francois Couperin, Charlemagne y Cesar Frank.

  1. FRANCOIS COUPERIN
  2. CHARLEMAGNE
  3. CESAR FRANCK
  4. ELSA TRIOLET
  5. VICTOR HUGO

Luego realizo un LEFT JOIN para unir los datos de la cantidad con la base de datos de colegios por puntos.

colegios_geo_b <- left_join(colegios_geo, wifi_x_colegios)
## Joining with `by = join_by(libelle)`
buffer_reproyectado <- buffer_colegios %>%
  st_transform(crs = 4236)

Mapeo las ubicaciones de los colegios con sus respectivos buffers de 500 metros y su relación con los Puntos WIFI.

ggmap(mapa_base) + 
  geom_sf(data = paris, 
          inherit.aes = FALSE, fill = NA) + 
  geom_sf(data = buffer_colegios,  
          fill= "green", size = 0.1, alpha = 0.05, color ="green", inherit.aes = FALSE) + 
  geom_sf(data = wifi_geo,  
          alpha = 0.5, inherit.aes = FALSE) +
  geom_sf(data = colegios_geo_b,  
          color = "blue", size = 2, inherit.aes = FALSE) + 
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

A continuación, mostrare un mapa donde vemos cuales son los colegios con mayor cantidad de Puntos WIFI próximos:

ggmap(mapa_base) + 
  geom_sf(data = paris, inherit.aes = FALSE, fill = NA) + 
  geom_sf(data = wifi_geo,  alpha = 0.2, inherit.aes = FALSE, color = "red") +
  geom_sf(data = colegios_geo_b,  aes(color = cantidad), size = 2, inherit.aes = FALSE) + 
  scale_color_viridis_c( direction = -1) + 
  labs(title = "Cantidad de puntos wifi a menos de 500m" ) +
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

Podríamos decir que los colegios con mayor conectividad pública se encuentran en el centro de la ciudad de París.

Por último, decidí probar otra forma de mostrar los datos, por lo cual cambie el mapa base por uno más neutro.

wifi_coord <- wifi_geo %>%
  select(nom_site) %>%
  cbind(st_coordinates(wifi_geo))
bbox_x <- st_bbox(paris)
class(bbox_x)
## [1] "bbox"
bbox_x <- as.numeric(bbox_x)
class(bbox_x)
## [1] "numeric"
mapa_base_x <- get_stamenmap(bbox = bbox_x, 
                           maptype = "toner", 
                           zoom = 12)
## Source : http://tile.stamen.com/toner/12/2073/1408.png
## Source : http://tile.stamen.com/toner/12/2074/1408.png
## Source : http://tile.stamen.com/toner/12/2075/1408.png
## Source : http://tile.stamen.com/toner/12/2076/1408.png
## Source : http://tile.stamen.com/toner/12/2073/1409.png
## Source : http://tile.stamen.com/toner/12/2074/1409.png
## Source : http://tile.stamen.com/toner/12/2075/1409.png
## Source : http://tile.stamen.com/toner/12/2076/1409.png

A este nuevo mapa base le agregue un mapa de calor o densidad de Puntos WIFI en relación a la ubicación de los colegios en la ciudad de París.

ggmap(mapa_base_x)+
stat_density2d(data = wifi_geo%>% cbind(., st_coordinates(wifi_geo)), 
               aes(x = X, y = Y, fill = ..density..), 
                geom = 'tile', contour = paris, alpha = 0.5)+ 
    geom_sf(data = paris,
            fill = NA, alpha = 0.5, inherit.aes = FALSE) +
  geom_sf(data = colegios_geo, size = 2, inherit.aes = FALSE) + 
  labs(title = "Concentración de puntos wifi",
       fill = "Densidad") + 
  scale_fill_viridis_c(option = "A", direction = -1) + 
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## ℹ The deprecated feature was likely used in the ggmap package.
##   Please report the issue at <https://github.com/dkahle/ggmap/issues>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 2 rows containing non-finite values (`stat_density2d()`).
## Warning: Removed 396 rows containing missing values (`geom_tile()`).

De esta forma podemos corroborar de otra forma visual la relación de los datos previos.

La mayor concentración de Puntos WIFI están en el centro de la ciudad de París, posiblemente relacionado con la confluencia de diversos medios de transporte y puntos turísticos en esta zona.

IMPORTACIÓN DE DATOS

Dado que la página de datos no contiene toda la información de la ciudad, decidí utilizar el servicio de OSM Open Street Maps.

En primer lugar, buscare y visualizare la ciudad de París

install.packages("osmdata")
## Installing package into 'C:/Users/Asus/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'osmdata' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'osmdata'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\Asus\AppData\Local\R\win-library\4.2\00LOCK\osmdata\libs\x64\osmdata.dll
## a C:\Users\Asus\AppData\Local\R\win-library\4.2\osmdata\libs\x64\osmdata.dll:
## Permission denied
## Warning: restored 'osmdata'
## 
## The downloaded binary packages are in
##  C:\Users\Asus\AppData\Local\Temp\Rtmpch4dSE\downloaded_packages
library(tidyverse)

library(sf)

library(ggmap)

library(osmdata)
## Warning: package 'osmdata' was built under R version 4.2.3
## Data (c) OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright
bbox_paris <- getbb("Paris, Francia")
mapa_paris<- get_stamenmap(bbox=bbox_paris,
                              maptype="toner-lite",
                              zoom=14)
## 84 tiles needed, this may take a while (try a smaller zoom).
## Source : http://tile.stamen.com/toner-lite/14/8293/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5633.png
## Source : http://tile.stamen.com/toner-lite/14/8293/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5634.png
## Source : http://tile.stamen.com/toner-lite/14/8293/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5635.png
## Source : http://tile.stamen.com/toner-lite/14/8293/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5636.png
## Source : http://tile.stamen.com/toner-lite/14/8293/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5637.png
## Source : http://tile.stamen.com/toner-lite/14/8293/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5638.png
## Source : http://tile.stamen.com/toner-lite/14/8293/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8294/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8295/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8296/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8297/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8298/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8299/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8300/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8301/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8302/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8303/5639.png
## Source : http://tile.stamen.com/toner-lite/14/8304/5639.png
ggmap(mapa_paris)

Por otro lado, descargué el perímetro de la ciudad de París utilizado el servidor de OSM.

poligono_paris <- getbb("Paris, Francia",
                            format_out = "sf_polygon")
ggmap(mapa_paris)+
  geom_sf(data=poligono_paris, inherit.aes = FALSE)
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

ggmap(mapa_paris)+
  geom_sf(data=poligono_paris, fill=NA, color="blue", size=1, inherit.aes = FALSE)+
  labs(title="Ciudad de París",
       subtitle="Límites de la ciudad de París",
       caption="Fuente: Open Street Map")+
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

Con el contexto delimitado procedo a iniciar un análisis de la relación de diversos tipos de comercios relacionado con la alimentación y la proximidad de los colegios. Es por esto que descargo la información de los comercios de fast food, cafés y restaurantes y los visualizo dentro del mapa generado previamente.

resto_paris <- opq(bbox_paris) %>%
  add_osm_feature(key = "amenity", value = c("fast_food", "restaurant","cafe"))
resto_paris
## $bbox
## [1] "48.8155755,2.224122,48.902156,2.4697602"
## 
## $prefix
## [1] "[out:xml][timeout:25];\n(\n"
## 
## $suffix
## [1] ");\n(._;>;);\nout body;"
## 
## $features
## [1] "[\"amenity\"~\"^(fast_food|restaurant|cafe)$\"]"
## 
## $osm_types
## [1] "node"     "way"      "relation"
## 
## attr(,"class")
## [1] "list"           "overpass_query"
## attr(,"nodes_only")
## [1] FALSE
resto_paris <- osmdata_sf(resto_paris)
resto_paris <- resto_paris$osm_points
dim(resto_paris)
## [1] 19607   439
ggmap(mapa_paris)+
  geom_sf(data=poligono_paris, fill=NA, color="blue", size=1, inherit.aes = FALSE)+
    geom_sf(data=resto_paris, inherit.aes = FALSE)+
  labs(title="Comercios",
       subtitle="París, Francia",
       caption="Fuente: Open Street Map")+
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

Limpio la base de datos, eliminando los valores sin datos de la columna amenity pero luego opto por filtrar sólo los valores que me interesan, fast food, cafés y restaurantes.

filtro<- filter(resto_paris, !is.na(amenity))
filtrob<- filter(resto_paris,amenity=="cafe"|  amenity=="fast_food"| amenity=="restaurant" )

Vuelvo a mapear la información para categorizar los valores por tipo de comercio.

ggmap(mapa_paris)+
  geom_sf(data=poligono_paris, fill=NA, color="blue", size=1, inherit.aes = FALSE)+
    geom_sf(data=filtrob, inherit.aes = FALSE, aes(color=amenity),  alpha = 0.1)+
  labs(title="Comercios",
       subtitle="París, Francia",
       color="Tipo",
       caption="Fuente: Open Street Map")+
  
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

Como se puede ver, varios valores se encuentran fuera del perimetro de la ciudad de París, por lo tanto selecciono los que me interesan, cruzando los datos con el límite de la ciudad.

resto_paris_b <- st_intersection(filtrob,paris)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
dim(resto_paris_b)
## [1] 12745   448
ggmap(mapa_paris)+
  geom_sf(data=poligono_paris, fill=NA, color="blue", size=1, inherit.aes = FALSE)+
    geom_sf(data=resto_paris_b, inherit.aes = FALSE, aes(color=amenity),  alpha = 0.2)+
  labs(title="Comercios",
       subtitle="París, Francia",
       color="Tipo",
       caption="Fuente: Open Street Map")+
  
  theme_void()
## Coordinate system already present. Adding new coordinate system, which will
## replace the existing one.

Ya con los datos filtrado y mapeados procedo a descubrir la cantidad de cada tipo de comercio.

resto_paris_c <-resto_paris_b%>%
  group_by(amenity) %>%
  summarise(cantidad=n())
resto_paris_c
## Simple feature collection with 3 features and 2 fields
## Geometry type: MULTIPOINT
## Dimension:     XY
## Bounding box:  xmin: 2.234865 ymin: 48.81723 xmax: 2.467387 ymax: 48.90148
## Geodetic CRS:  WGS 84
## # A tibble: 3 × 3
##   amenity    cantidad                                                   geometry
##   <chr>         <int>                                           <MULTIPOINT [°]>
## 1 cafe           2132 ((2.250075 48.87034), (2.263552 48.87663), (2.263856 48.8…
## 2 fast_food      2434 ((2.261918 48.87773), (2.269346 48.85855), (2.276139 48.8…
## 3 restaurant     8179 ((2.467387 48.83397), (2.234865 48.86885), (2.240439 48.8…

De esta forma, podemos ver que de los tres tipos de comercios analizados, dentro de la ciudad el que más hay es: 1. Restaurantes 2. Fast food 3. Cafeterías

GEOCODIFICACIÓN

Finalmente decido cargar la base de datos de Vivienda social financiada en París. Sin embargo al visualizar los datos veo que las direcciones estaban muy diferentes, habían varios tipos de direcciones, por este motivo opto por filtrarlas en excel y sólo quedarme con los datos del año 2020.

install.packages("Rcpp")
## Installing package into 'C:/Users/Asus/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'Rcpp' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'Rcpp'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\Asus\AppData\Local\R\win-library\4.2\00LOCK\Rcpp\libs\x64\Rcpp.dll a
## C:\Users\Asus\AppData\Local\R\win-library\4.2\Rcpp\libs\x64\Rcpp.dll:
## Permission denied
## Warning: restored 'Rcpp'
## 
## The downloaded binary packages are in
##  C:\Users\Asus\AppData\Local\Temp\Rtmpch4dSE\downloaded_packages
viv_social<-read_csv2("Data/logements_sociaux_2020.csv")
## ℹ Using "','" as decimal and "'.'" as grouping mark. Use `read_delim()` for more control.
## Rows: 41 Columns: 19
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ";"
## chr (6): Adresse du programme, Ville, Bailleur social, Mode de réalisation,...
## dbl (9): Identifiant livraison, Code postal, Année du financement - agréme...
## num (3): COORD_X_L93, COORD_Y_L93, geo_point_2d
## lgl (1): Commentaires
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
install.packages("tmap")
## Installing package into 'C:/Users/Asus/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'tmap' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\Asus\AppData\Local\Temp\Rtmpch4dSE\downloaded_packages
install.packages("tmaptools")
## Installing package into 'C:/Users/Asus/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'tmaptools' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\Asus\AppData\Local\Temp\Rtmpch4dSE\downloaded_packages
library("tmap")
## Warning: package 'tmap' was built under R version 4.2.3
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
library("tmaptools")
## Warning: package 'tmaptools' was built under R version 4.2.3

Afortunadamente la base de datos ya cuenta con una columna de cantidades de viviendas financiadas por cada ubicación, por lo que sólo ordenare los valores de mayor a menor y visualizare los primeros diez puntos.

cantidad <- viv_social %>% 
  arrange(desc(`Nombre total de logements financés`))
head(cantidad, 10)
## # A tibble: 10 × 19
##    `Identifiant livraison` `Adresse du programme`          `Code postal` Ville
##                      <dbl> <chr>                                   <dbl> <chr>
##  1                    3660 61, RUE DE CHARONNE                     75011 Paris
##  2                    3647 5, RUE AGRIPPA D'AUBIGNE                75004 Paris
##  3                    3648 5, RUE DU BESSIN                        75015 Paris
##  4                    3587 11, RUE MURGER                          75019 Paris
##  5                    3592 120, RUE DE CLIGNANCOURT                75018 Paris
##  6                    3597 13, RUE LEBOUTEUX                       75017 Paris
##  7                    3620 21, RUE DES FONTAINES DU TEMPLE         75003 Paris
##  8                    3624 27, RUE BOURET                          75019 Paris
##  9                    3582 102, RUE DE LA JONQUIERE                75017 Paris
## 10                    3585 107, RUE DE TOCQUEVILLE                 75017 Paris
## # ℹ 15 more variables: `Année du financement - agrément` <dbl>,
## #   `Bailleur social` <chr>, `Nombre total de logements financés` <dbl>,
## #   `Dont nombre de logements PLA I` <dbl>,
## #   `Dont nombre de logements PLUS` <dbl>,
## #   `Dont nombre de logements PLUS CD` <dbl>,
## #   `Dont nombre de logements PLS` <dbl>, `Mode de réalisation` <chr>,
## #   Commentaires <lgl>, Arrondissement <dbl>, `Nature de programme` <chr>, …

A la dirección original de la base de datos en Adresse du programme le agrego el dato de la ciudad y el país para poder geocodificar las ubicaciones con OSM.

cantidad_b <- cantidad %>%
  mutate(direccion = paste0(`Adresse du programme`, ", PARIS, France"))
direcciones_localizadas <- geocode_OSM(cantidad_b$direccion, 
                           as.data.frame = TRUE)
head(direcciones_localizadas)
##                                     query      lat      lon  lat_min  lat_max
## 1      61, RUE DE CHARONNE, PARIS, France 48.85346 2.379589 48.85341 48.85351
## 2 5, RUE AGRIPPA D'AUBIGNE, PARIS, France 48.85019 2.362166 48.85014 48.85024
## 3         5, RUE DU BESSIN, PARIS, France 48.83091 2.306042 48.83086 48.83096
## 4           11, RUE MURGER, PARIS, France 48.87934 2.375486 48.87929 48.87939
## 5 120, RUE DE CLIGNANCOURT, PARIS, France 48.89360 2.349247 48.89355 48.89365
## 6        13, RUE LEBOUTEUX, PARIS, France 48.88324 2.315675 48.88319 48.88329
##    lon_min  lon_max
## 1 2.379539 2.379639
## 2 2.362116 2.362216
## 3 2.305992 2.306092
## 4 2.375436 2.375536
## 5 2.349197 2.349297
## 6 2.315625 2.315725

Unire las tablas para poder tener los valores del query recientemente generado.

cantidad_b_geo <- cantidad_b %>%
  left_join(direcciones_localizadas, by = c("direccion" = "query"))
cantidad_b_geo
## # A tibble: 41 × 26
##    `Identifiant livraison` `Adresse du programme`          `Code postal` Ville
##                      <dbl> <chr>                                   <dbl> <chr>
##  1                    3660 61, RUE DE CHARONNE                     75011 Paris
##  2                    3647 5, RUE AGRIPPA D'AUBIGNE                75004 Paris
##  3                    3648 5, RUE DU BESSIN                        75015 Paris
##  4                    3587 11, RUE MURGER                          75019 Paris
##  5                    3592 120, RUE DE CLIGNANCOURT                75018 Paris
##  6                    3597 13, RUE LEBOUTEUX                       75017 Paris
##  7                    3620 21, RUE DES FONTAINES DU TEMPLE         75003 Paris
##  8                    3624 27, RUE BOURET                          75019 Paris
##  9                    3582 102, RUE DE LA JONQUIERE                75017 Paris
## 10                    3585 107, RUE DE TOCQUEVILLE                 75017 Paris
## # ℹ 31 more rows
## # ℹ 22 more variables: `Année du financement - agrément` <dbl>,
## #   `Bailleur social` <chr>, `Nombre total de logements financés` <dbl>,
## #   `Dont nombre de logements PLA I` <dbl>,
## #   `Dont nombre de logements PLUS` <dbl>,
## #   `Dont nombre de logements PLUS CD` <dbl>,
## #   `Dont nombre de logements PLS` <dbl>, `Mode de réalisation` <chr>, …

Visualizo los datos con Leaflet

library(leaflet)
## Warning: package 'leaflet' was built under R version 4.2.3
leaflet() %>%
  addTiles() %>% 
  addCircleMarkers(data = cantidad_b_geo, lng = ~lon, lat = ~lat)

Probare crear un tipo de función para poder mapear las ubicaciones.

geocode_verbose <- function(x){
  
  geocode_direcciones <- geocode_OSM(x, as.data.frame = TRUE) 
  geocode_direcciones$direccion <- geocode_direcciones$query
  print(x)
  df <- select(geocode_direcciones, direccion, lat, lon)
}

Creare una lista para poder utilizar la función.

direcciones <- list(cantidad_b$direccion)
direcciones_geo <- map(direcciones, geocode_verbose) %>% 
  reduce(rbind) 
##  [1] "61, RUE DE CHARONNE, PARIS, France"            
##  [2] "5, RUE AGRIPPA D'AUBIGNE, PARIS, France"       
##  [3] "5, RUE DU BESSIN, PARIS, France"               
##  [4] "11, RUE MURGER, PARIS, France"                 
##  [5] "120, RUE DE CLIGNANCOURT, PARIS, France"       
##  [6] "13, RUE LEBOUTEUX, PARIS, France"              
##  [7] "21, RUE DES FONTAINES DU TEMPLE, PARIS, France"
##  [8] "27, RUE BOURET, PARIS, France"                 
##  [9] "102, RUE DE LA JONQUIERE, PARIS, France"       
## [10] "107, RUE DE TOCQUEVILLE, PARIS, France"        
## [11] "8, RUE DAUTANCOURT, PARIS, France"             
## [12] "123, RUE DU CHEMIN VERT, PARIS, France"        
## [13] "9, RUE LEMERCIER, PARIS, France"               
## [14] "16, RUE SAULNIER, PARIS, France"               
## [15] "4, RUE DES CAMELIAS, PARIS, France"            
## [16] "124, RUE DES PYRENEES, PARIS, France"          
## [17] "23, RUE DROUOT, PARIS, France"                 
## [18] "7, RUE ALPHONSE PENAUD, PARIS, France"         
## [19] "12, RUE D'ANNAM, PARIS, France"                
## [20] "21, RUE BREY, PARIS, France"                   
## [21] "85, AVENUE EMILE ZOLA, PARIS, France"          
## [22] "9, RUE DE CHATEAUDUN, PARIS, France"           
## [23] "5, RUE SIMONET, PARIS, France"                 
## [24] "71, RUE SAINT DOMINIQUE, PARIS, France"        
## [25] "143, RUE DE VAUGIRARD, PARIS, France"          
## [26] "254, RUE PYRENEES, PARIS, France"              
## [27] "10, PASSAGE COURTOIS, PARIS, France"           
## [28] "10 BIS, RUE LAMARTINE, PARIS, France"          
## [29] "17, RUE DE LA DUEE, PARIS, France"             
## [30] "59, RUE CASTAGNARY, PARIS, France"             
## [31] "16, RUE DE BELFORT, PARIS, France"             
## [32] "97, RUE DE LA JONQUIERE, PARIS, France"        
## [33] "9, RUE SAINT SAUVEUR, PARIS, France"           
## [34] "144, BD DE MENILMONTANT, PARIS, France"        
## [35] "87, RUE BUZENVAL, PARIS, France"               
## [36] "10, RUE DE PARADIS, PARIS, France"             
## [37] "37, BD DE BELLEVILLE, PARIS, France"           
## [38] "17, RUE DU DOCTEUR PAUL BROUSSE, PARIS, France"
## [39] "5, RUE SIDI BRAHIM, PARIS, France"             
## [40] "61, BD SAINT JACQUES, PARIS, France"           
## [41] "9, AVENUE DE LA PORTE CHAUMONT, PARIS, France"
head(direcciones_geo, 10)
##                                         direccion      lat      lon
## 1              61, RUE DE CHARONNE, PARIS, France 48.85346 2.379589
## 2         5, RUE AGRIPPA D'AUBIGNE, PARIS, France 48.85019 2.362166
## 3                 5, RUE DU BESSIN, PARIS, France 48.83091 2.306042
## 4                   11, RUE MURGER, PARIS, France 48.87934 2.375486
## 5         120, RUE DE CLIGNANCOURT, PARIS, France 48.89360 2.349247
## 6                13, RUE LEBOUTEUX, PARIS, France 48.88324 2.315675
## 7  21, RUE DES FONTAINES DU TEMPLE, PARIS, France 48.86579 2.358216
## 8                   27, RUE BOURET, PARIS, France 48.88201 2.373177
## 9         102, RUE DE LA JONQUIERE, PARIS, France 48.89504 2.317751
## 10         107, RUE DE TOCQUEVILLE, PARIS, France 48.88862 2.305906

Unifico ambas tablas, la nueva con la anterior para luego pasar el paso final.

cantidad_b_geo <- left_join(cantidad_b, direcciones_geo)
## Joining with `by = join_by(direccion)`
head(cantidad_b_geo)
## # A tibble: 6 × 22
##   `Identifiant livraison` `Adresse du programme`   `Code postal` Ville
##                     <dbl> <chr>                            <dbl> <chr>
## 1                    3660 61, RUE DE CHARONNE              75011 Paris
## 2                    3647 5, RUE AGRIPPA D'AUBIGNE         75004 Paris
## 3                    3648 5, RUE DU BESSIN                 75015 Paris
## 4                    3587 11, RUE MURGER                   75019 Paris
## 5                    3592 120, RUE DE CLIGNANCOURT         75018 Paris
## 6                    3597 13, RUE LEBOUTEUX                75017 Paris
## # ℹ 18 more variables: `Année du financement - agrément` <dbl>,
## #   `Bailleur social` <chr>, `Nombre total de logements financés` <dbl>,
## #   `Dont nombre de logements PLA I` <dbl>,
## #   `Dont nombre de logements PLUS` <dbl>,
## #   `Dont nombre de logements PLUS CD` <dbl>,
## #   `Dont nombre de logements PLS` <dbl>, `Mode de réalisation` <chr>,
## #   Commentaires <lgl>, Arrondissement <dbl>, `Nature de programme` <chr>, …

Modificare el CRS y mapeare los datos generados con la función nuevamente.Por cada punto tendré en cuenta la cantidad por ubicación y que se pueda ver claramente.

cantidad_b_geo <- st_as_sf(cantidad_b_geo, coords = c("lon", "lat"), crs = 4326)
leaflet() %>%
  addTiles() %>% 
  addCircleMarkers(data = cantidad_b_geo, radius = ~`Nombre total de logements financés`)

Pruebo nuevamente con otro tipo de función por lo que procedo a averiguar la cantidad de datos u observaciones que tengo.

1:nrow(cantidad_b)
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

CREO FUNCION

geocode_df <- function(x, direccion = y){
  ## x es un dataframe, y es el nombre de la variable
  vector_direcciones <- x$direccion
  geocode_direcciones <- geocode_OSM(vector_direcciones, as.data.frame = TRUE) 
  x$lat <- geocode_direcciones$lat
  x$lon <- geocode_direcciones$lon
  x

}
direcciones_geo2  <- NULL
total <- nrow(cantidad_b)
for(i in 1:total) {
  direccion_a_geolocalizar <- cantidad_b[i,]
  direccion_unica_geo <- geocode_df(direccion_a_geolocalizar, direccion)
  estado <- paste0(i,"/", total, ": ", direccion_unica_geo$direccion )
  print(estado)
  direcciones_geo2 <- rbind(direcciones_geo2, direccion_unica_geo)
}
## [1] "1/41: 61, RUE DE CHARONNE, PARIS, France"
## [1] "2/41: 5, RUE AGRIPPA D'AUBIGNE, PARIS, France"
## [1] "3/41: 5, RUE DU BESSIN, PARIS, France"
## [1] "4/41: 11, RUE MURGER, PARIS, France"
## [1] "5/41: 120, RUE DE CLIGNANCOURT, PARIS, France"
## [1] "6/41: 13, RUE LEBOUTEUX, PARIS, France"
## [1] "7/41: 21, RUE DES FONTAINES DU TEMPLE, PARIS, France"
## [1] "8/41: 27, RUE BOURET, PARIS, France"
## [1] "9/41: 102, RUE DE LA JONQUIERE, PARIS, France"
## [1] "10/41: 107, RUE DE TOCQUEVILLE, PARIS, France"
## [1] "11/41: 8, RUE DAUTANCOURT, PARIS, France"
## [1] "12/41: 123, RUE DU CHEMIN VERT, PARIS, France"
## [1] "13/41: 9, RUE LEMERCIER, PARIS, France"
## [1] "14/41: 16, RUE SAULNIER, PARIS, France"
## [1] "15/41: 4, RUE DES CAMELIAS, PARIS, France"
## [1] "16/41: 124, RUE DES PYRENEES, PARIS, France"
## [1] "17/41: 23, RUE DROUOT, PARIS, France"
## [1] "18/41: 7, RUE ALPHONSE PENAUD, PARIS, France"
## [1] "19/41: 12, RUE D'ANNAM, PARIS, France"
## [1] "20/41: 21, RUE BREY, PARIS, France"
## [1] "21/41: 85, AVENUE EMILE ZOLA, PARIS, France"
## [1] "22/41: 9, RUE DE CHATEAUDUN, PARIS, France"
## [1] "23/41: 5, RUE SIMONET, PARIS, France"
## [1] "24/41: 71, RUE SAINT DOMINIQUE, PARIS, France"
## [1] "25/41: 143, RUE DE VAUGIRARD, PARIS, France"
## [1] "26/41: 254, RUE PYRENEES, PARIS, France"
## [1] "27/41: 10, PASSAGE COURTOIS, PARIS, France"
## [1] "28/41: 10 BIS, RUE LAMARTINE, PARIS, France"
## [1] "29/41: 17, RUE DE LA DUEE, PARIS, France"
## [1] "30/41: 59, RUE CASTAGNARY, PARIS, France"
## [1] "31/41: 16, RUE DE BELFORT, PARIS, France"
## [1] "32/41: 97, RUE DE LA JONQUIERE, PARIS, France"
## [1] "33/41: 9, RUE SAINT SAUVEUR, PARIS, France"
## [1] "34/41: 144, BD DE MENILMONTANT, PARIS, France"
## [1] "35/41: 87, RUE BUZENVAL, PARIS, France"
## [1] "36/41: 10, RUE DE PARADIS, PARIS, France"
## [1] "37/41: 37, BD DE BELLEVILLE, PARIS, France"
## [1] "38/41: 17, RUE DU DOCTEUR PAUL BROUSSE, PARIS, France"
## [1] "39/41: 5, RUE SIDI BRAHIM, PARIS, France"
## [1] "40/41: 61, BD SAINT JACQUES, PARIS, France"
## [1] "41/41: 9, AVENUE DE LA PORTE CHAUMONT, PARIS, France"
head(direcciones_geo2, 10)
## # A tibble: 10 × 22
##    `Identifiant livraison` `Adresse du programme`          `Code postal` Ville
##                      <dbl> <chr>                                   <dbl> <chr>
##  1                    3660 61, RUE DE CHARONNE                     75011 Paris
##  2                    3647 5, RUE AGRIPPA D'AUBIGNE                75004 Paris
##  3                    3648 5, RUE DU BESSIN                        75015 Paris
##  4                    3587 11, RUE MURGER                          75019 Paris
##  5                    3592 120, RUE DE CLIGNANCOURT                75018 Paris
##  6                    3597 13, RUE LEBOUTEUX                       75017 Paris
##  7                    3620 21, RUE DES FONTAINES DU TEMPLE         75003 Paris
##  8                    3624 27, RUE BOURET                          75019 Paris
##  9                    3582 102, RUE DE LA JONQUIERE                75017 Paris
## 10                    3585 107, RUE DE TOCQUEVILLE                 75017 Paris
## # ℹ 18 more variables: `Année du financement - agrément` <dbl>,
## #   `Bailleur social` <chr>, `Nombre total de logements financés` <dbl>,
## #   `Dont nombre de logements PLA I` <dbl>,
## #   `Dont nombre de logements PLUS` <dbl>,
## #   `Dont nombre de logements PLUS CD` <dbl>,
## #   `Dont nombre de logements PLS` <dbl>, `Mode de réalisation` <chr>,
## #   Commentaires <lgl>, Arrondissement <dbl>, `Nature de programme` <chr>, …
viv_social_geo <- cantidad_b %>%
  left_join(direcciones_geo2, by = "direccion" ) %>%
  filter(!is.na(lat) & !is.na(lon)) %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326)
ggplot() + 
  geom_sf(data = viv_social_geo )

Visualizo los datos recién geocodificados teniendo en cuenta la cantidad por cada punto.

leaflet() %>%
  addProviderTiles(provider = "CartoDB.Positron" ) %>%
  addCircleMarkers(data = viv_social_geo, 
                   radius = ~`Nombre total de logements financés.x`, 
                   color = "red")

Por último, con los datos corroborados procedo a la edición para una mejor visualización.

paleta <- colorNumeric(palette = c("#c7e9b4", "#1d91c0", "#081d58" ), 
                       domain = viv_social_geo$`Nombre total de logements financés.x`)

viv_social_geob <- viv_social_geo %>%
  mutate(leyenda = paste0( "Tipo de obra: ", `Mode de réalisation.x`, "</br>", 
                           "En total se realizaron: " , "<b>",`Nombre total de logements financés.x`, "</b>","</br>", " Barrio:"  , Arrondissement.x
    
  ))

leaflet() %>%
  addPolygons(data = paris_b, fillColor = NA, color = "grey") %>%
  addProviderTiles(provider = "CartoDB.Positron" ) %>%
  addCircleMarkers(data = colegios_geo_b,
                   color = "olive",
                   label = ~libelle,
                   radius = 0.5, 
                   fillOpacity = 0.4, 
                   opacity = 0.5)%>%
  addCircleMarkers(data = viv_social_geob, 
                   color = ~paleta(`Nombre total de logements financés.x`), 
                   popup = ~leyenda,
                   label = ~direccion,
                   radius = 4) %>%
    addLegend(data = viv_social_geob,
              "bottomright", 
              pal = paleta, 
              values = ~`Nombre total de logements financés.x`,
              title = "Viviendas financiadas",
              opacity = 1)

Como se puede observar, construí un mapa con los barrios de la ciudad de París, las ubicaciones de las viviendas sociales financiadas y los colegios. Por cada ubicación se puede ver su leyenda, con nombres con datos numéricos y de barrio.

Al comparar los distintos mapas podemos ver que no hay grandes diferencias en cuanto el mapeo de las ubicaciones.